/*
 * @Author: yzr
 * @Date: 2023-09-12 16:22:31
 * @LastEditors: yzr
 * @LastEditTime: 2023-10-12 10:24:40
 * @Description: 登录页
 * @FilePath: /utilization/src/pages/login/index.tsx
 */
import { useState, useCallback, useEffect } from 'react';
import { Image, Button, Form, Input, Checkbox } from 'antd';
import { useNavigate } from 'react-router-dom';
import { useRequest } from 'ahooks';
import Icon from '@/components/SvgIcon';
import { loginAPI } from '@/api/login';
import loginPic from '@/assets/image/loginPic.png';

import './index.scss';

const Login: React.FC = () => {
  const navigate = useNavigate();
  const [form] = Form.useForm();
  const values = Form.useWatch([], form);

  const [loading, setLoading] = useState(false);
  const [submittable, setSubmittable] = useState(false);

  const validate = useCallback(async () => {
    try {
      await form.validateFields({ validateOnly: true });
      setSubmittable(true);
    } catch (error) {
      setSubmittable(false);
    }
  }, [form]);

  useEffect(() => {
    validate();
  }, [values, validate]);

  useEffect(() => {
    const loginInfo = localStorage.getItem('loginInfo');
    if (loginInfo) {
      const info = JSON.parse(loginInfo);
      // console.log(info);
      form.setFieldsValue({
        userName: info?.userName,
        password: info?.password,
        savePassword: true,
      });
    }
  }, [form]);

  const { run: login } = useRequest(
    () => loginAPI({ userName: values.userName, password: values.password }),
    {
      manual: true,
      onSuccess: res => {
        localStorage.setItem('satoken', JSON.stringify(res.data));
        if (values.savePassword) {
          localStorage.setItem(
            'loginInfo',
            JSON.stringify({
              userName: values.userName,
              password: values.password,
            })
          );
        } else {
          localStorage.removeItem('loginInfo');
        }
        navigate('/');
      },
      onError: err => {
        console.log('error===>', err, loading);
      },
      onFinally: () => {
        setLoading(false);
      },
    }
  );

  const submit = async () => {
    setLoading(true);
    await login();
    setTimeout(() => {
      setLoading(false);
    });
  };

  return (
    <div className="loginPage">
      <div className="picPart">
        <div className="picTitle">
          <div className="appIcon" />
          <div className="title">设备利用率可视化系统</div>
        </div>
        <div className="loginPic">
          <Image src={loginPic} preview={false} />
        </div>
        <div className="welcome">欢迎使用！</div>
        <div className="introduce">
          面向实验室仪器，提供标准一致、数据源统一、精准高效的利用率统计，用户可以通过多维度分析，提升设备有效利用率
        </div>
      </div>

      <div className="formPart">
        <div className="loginTitle">登录您的账户</div>
        <div className="subTitle">嘿，输入您的详细信息以登录您的帐户</div>
        <Form className="form" form={form} layout="vertical" onFinish={submit}>
          <Form.Item
            name="userName"
            label="请输入用户名"
            required={false}
            rules={[{ required: true, message: '请输入用户名' }]}>
            <Input placeholder="请输入您的用户名" />
          </Form.Item>
          <Form.Item
            name="password"
            label="请输入密码"
            required={false}
            rules={[{ required: true, message: '请输入密码' }]}
            style={{ marginBottom: '12px' }}>
            <Input.Password
              placeholder="请输入您的密码"
              iconRender={visible => (
                <div style={{ color: '#d9d9d9' }}>
                  {visible ? (
                    <Icon name="icon-zhengyan" />
                  ) : (
                    <Icon name="icon-biyan" />
                  )}
                </div>
              )}
            />
          </Form.Item>
          <Form.Item name="savePassword" valuePropName="checked">
            <Checkbox>记住密码</Checkbox>
          </Form.Item>
          <Form.Item>
            <Button
              type="primary"
              disabled={!submittable}
              loading={loading}
              htmlType="submit">
              登录
            </Button>
          </Form.Item>
        </Form>
      </div>
    </div>
  );
};

export default Login;
